package cn.bocai.pc.web.portal;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;        
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bocai.pc.model.BcUser;
import cn.bocai.pc.model.DataUtils;
import cn.bocai.pc.service.BcUserService;
import cn.bocai.pc.util.MD5Utils;
import cn.bocai.pc.util.UUIDUtils;

@Controller
@RequestMapping("/result")
public class ResultController {
	@Autowired
	private BcUserService userService;
	//用户注册信息保存
     @RequestMapping(value="/register")
     public String doPost(HttpServletRequest request, HttpServletResponse response,BcUser bu,Model m) { 
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/register.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 String selectName = userService.selectEmail(bu.getEmail());
            	 if("1".equals(selectName)){
            		 m.addAttribute("msg",bu.getEmail()+"已存在");
            	 }else if("0".equals(selectName)){
            		 bu.setUserId(UUIDUtils.getUUID32());
                	 bu.setUsername(bu.getUsername());
                	 bu.setPassword(MD5Utils.md5(bu.getPassword()));
                	 bu.setEmail(bu.getEmail());
                	 bu.setRegisterTime(DataUtils.now());
                	 bu.setRegisterIp(getIpAddr(request,response));
                	 int register = userService.insertRegister(bu);
                	 if(!"0".equals(register)){
                	   m.addAttribute("msg","注册成功,请登入");
                	   m.addAttribute("skipUrl","/skip/login.do");
                	 }
            	 }
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
         return "page/prompt/publicPrompt";
     }        

     //用户登入
     @RequestMapping("/doLogin")
     public String doLogin(HttpServletRequest request, HttpServletResponse response,BcUser logbu,Model m){
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/login.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 
            	 publicLogin(request,logbu,m,"page");
            	 
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
        return "page/prompt/publicPrompt";
     }
     
     //用户头部右上角登入
     @RequestMapping("/headLogin")
     public String headLogin(HttpServletRequest request, HttpServletResponse response,BcUser logbu,Model m){
       	 
        publicLogin(request,logbu,m,"head");
            
         return "page/prompt/publicPrompt";
     }
     
     
     
     //用户安全退出
     @RequestMapping("/dologout")
       public String dologout(HttpServletRequest request){
  	   //TODO 安全退出的时候需要把用户信息从session中消除
    	 request.getSession().removeAttribute("selectLogin");
  		return "page/accounts/login";
       }
     
     
     //用户注册的时候输入用户名进行ajax校验用户名是否已存在
     @RequestMapping("/AjaxName")
       public void  AjaxName(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	 response.setContentType("text/html;charset=utf-8");  
    	 String name = request.getParameter("c");
    	 //TODO 调取dao层的数据进行判断返回(未测)
    	 PrintWriter out = response.getWriter();
    	 String selectName = userService.selectNameExist(name);
    	 if("1".equals(selectName)){
    		 out.println("已被注册");   
    	 }else if("0".equals(selectName)){
    		 out.println("可以使用");   
    	 }
         out.flush();        
         out.close();
       }
     
     
   //TODO 邮件发送请求找回密码
     @RequestMapping("/sendingEmail")
     public String sendingEmail(HttpServletRequest request, HttpServletResponse response,BcUser logbu,Model m){
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/forgetPwd.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 
            	 m.addAttribute("msg","邮件已发送，请注意查收");
            	 
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
         return "page/prompt/publicPrompt";
     }
     
     
    //登入以后修改密码
     @RequestMapping("/doModifyPwd")
     public String doModifyPwd(HttpServletRequest request, HttpServletResponse response,Model m){
         String validateC = (String) request.getSession().getAttribute("validateCode"); 
         String oldPaw =MD5Utils.md5(request.getParameter("password")) ;
    	 String newPaw =MD5Utils.md5(request.getParameter("newPwd"));
         String veryCode = request.getParameter("securityCode");
         m.addAttribute("skipUrl","/skip/afterLogin/alterPassword.do");
         if(veryCode==null||"".equals(veryCode)||"undefined".equals(veryCode)){
        	 m.addAttribute("msg","验证码不能为空");
         }else{        
             if(validateC.equalsIgnoreCase(veryCode)){
            	 BcUser attribute = (BcUser)request.getSession().getAttribute("selectLogin");
            	 String password = attribute.getPassword();
            	 if(!password.equals(oldPaw)){
            		 m.addAttribute("msg","输入密码有误");
            	 }else{
            		 //TODO  修改密码
            		 HashMap<String, Object> map = new HashMap<String, Object>();
            		 map.put("userId", attribute.getUserId());
            		 map.put("password", newPaw);
            		 int updateUserPaw = userService.updateUserPaw(map);
            		 if(!"0".equals(updateUserPaw)){
            			 request.getSession().removeAttribute("selectLogin");
            			 m.addAttribute("msg","密码修改成功");
            			 m.addAttribute("skipUrl","/skip/login.do");
            		 }
            	 }
            	 
             }else{        
                 m.addAttribute("msg","输入验证码有误");
             }        
         }        
         return "page/prompt/publicPrompt";
     }
     
     
     
     
     
     

//到客户端查询用户的ip地址
     private String getIpAddr(HttpServletRequest request, HttpServletResponse response) {   
          String ipAddress = null;   
          //ipAddress = this.getRequest().getRemoteAddr();   
          ipAddress = request.getHeader("x-forwarded-for");   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
           ipAddress =request.getHeader("Proxy-Client-IP");   
          }   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
              ipAddress = request.getHeader("WL-Proxy-Client-IP");   
          }   
          if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
           ipAddress = request.getRemoteAddr();   
           if(ipAddress.equals("127.0.0.1")){   
            //根据网卡取本机配置的IP   
            InetAddress inet=null;   
         try {   
          inet = InetAddress.getLocalHost();   
         } catch (UnknownHostException e) {   
          e.printStackTrace();   
         }   
         ipAddress= inet.getHostAddress();   
           }   
                 
          }   
       
          //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割   
          if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15   
              if(ipAddress.indexOf(",")>0){   
                  ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));   
              }   
          }   
          return ipAddress;    
       }   
     
     
     public void publicLogin(HttpServletRequest request,BcUser logbu,Model m,String judge){
    	 if("".equals(logbu.getUsername())||null==logbu.getUsername()||"".equals(logbu.getPassword())||null==logbu.getPassword()){
    		 m.addAttribute("msg","用户名或密码不能为空");
    		 if("page".equals(judge)){
    			 m.addAttribute("skipUrl","/skip/login.do");
     		  }else{
     			 m.addAttribute("skipUrl","/skip/login.do");
     		  }
    	 }else{
    		 logbu.setPassword(MD5Utils.md5(logbu.getPassword()));
        	 BcUser selectLogin = userService.selectLogin(logbu);
        	 if(null==selectLogin){
        		 m.addAttribute("msg","用户名或密码错误");
        		 if("page".equals(judge)){
        			 m.addAttribute("skipUrl","/skip/login.do");
         		  }else{
         			 m.addAttribute("skipUrl","/skip/login.do");
         		  }
                 
        	 }else{
        		 m.addAttribute("msg","登入成功，谢谢！");
        		 request.getSession().setAttribute("selectLogin", selectLogin);
        		 m.addAttribute("skipUrl","/skip/afterLogin/afLoCollect.do");
        		 
        	 }
        	   
          }
     }
     
}
